﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace LibarayMS
{
    public partial class Frm_reader_manage : Form
    {
        private int rrid;
        private string mname;
        public event myDelegate returnEvent;
        public event myDelegate logoutEvent;
        public Frm_reader_manage(string mname)
        {
            this.mname = mname;
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            returnEvent();
            this.Close();
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            logoutEvent();
            this.Close();
        }

        protected void bind_reader_info()
        {
            MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=my_db1;UID=root;PWD=123456");
            conn.Open();
            string str = "select RRID,RID,RName,a.RTID,sex,tel,tmp_borrow_num,acc_borrow_num,register_date,effiency_date,borrow_limit,day_limit,volate_num,state,remark from reader_info a,reader_type b where a.RTID=b.RTID;";
            MySqlDataAdapter msda = new MySqlDataAdapter(str, conn);
            DataTable dt = new DataTable();
            msda.Fill(dt);
            conn.Close();
            lv_reader.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                ListViewItem myitem = new ListViewItem(dr["RID"].ToString());
                myitem.SubItems.Add(dr["RName"].ToString());
                if (dr["RTID"].ToString() == "0")
                {
                    myitem.SubItems.Add("学生");
                }
                else if (dr["RTID"].ToString() == "1")
                {
                    myitem.SubItems.Add("教师");
                }
                else
                {
                    myitem.SubItems.Add("职工");
                }
                myitem.SubItems.Add(dr["sex"].ToString()=="0"?"女":"男");
                myitem.SubItems.Add(dr["tel"].ToString());
                myitem.SubItems.Add(dr["tmp_borrow_num"].ToString());
                myitem.SubItems.Add(dr["acc_borrow_num"].ToString());
                myitem.SubItems.Add(Convert.ToDateTime(dr["register_date"]).ToString("yyyy-MM-dd"));
                myitem.SubItems.Add(Convert.ToDateTime(dr["effiency_date"]).ToString("yyyy-MM-dd"));
                myitem.SubItems.Add(dr["borrow_limit"].ToString());
                myitem.SubItems.Add(dr["day_limit"].ToString());
                myitem.SubItems.Add(dr["volate_num"].ToString());
                myitem.SubItems.Add(dr["state"]. ToString()=="0"?"正常":"违规");
                myitem.SubItems.Add(dr["remark"].ToString());
                //隐藏列RRID
                myitem.SubItems.Add(dr["RRID"].ToString());
                lv_reader.Items.Add(myitem);
            }
        }

        protected void clearTextBox()
        {
            txt_RName.Text = "";
            cb_rtype.Text = "";
            btn_sex1.Checked= true;
            btn_sex2.Checked= false;
            nu_curr.Value = 0;
            nu_total.Value = 0;
            nu_violate.Value = 0;
            txt_tel.Text = "";
            dt_effi.Value = DateTime.Now.Date;
            cmb_state.Text = "";
            txt_remark.Text = "";
            lbl_status.Text = "添加";
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            string RName=txt_RName.Text.Trim();
            string RType=cb_rtype.Text.Trim();
            //0--女，1--男
            int sex=btn_sex1.Checked==true ? 1 : 0;
            int currbor = int.Parse(nu_curr.Value.ToString());
            int totalbor = int.Parse(nu_total.Value.ToString());
            string tel=txt_tel.Text.Trim();
            string effiency = dt_effi.Value.ToString("yyyy-MM-dd");
            //0--正常，1--违规
            int state = cmb_state.Text == "违规" ? 1 : 0;
            int violatenum=int.Parse(nu_violate.Value.ToString());
            string remark=txt_remark.Text.Trim();
            if (RName == "")
            {
                lbl_note.Text = "姓名不能为空！";
                lbl_note.ForeColor = Color.Red;
                txt_RName.Focus();
            }
            else if (RType == "")
            {
                lbl_note.Text = "读者类别不能为空！";
                lbl_note.ForeColor = Color.Red;
                cb_rtype.Focus();
            }
            else if (cmb_state.Text.Trim() == "")
            {
                lbl_note.Text = "状态不能为空！";
                lbl_note.ForeColor = Color.Red;
                cmb_state.Focus();
            }
            else if (currbor > totalbor)
            {
                lbl_note.Text = "现借数量不能大于已借数量！";
                lbl_note.ForeColor = Color.Red;
                nu_curr.Focus();
            }
            else if (state == 1 && violatenum == 0)
            {
                lbl_note.Text = "违规次数和状态矛盾！";
                lbl_note.ForeColor = Color.Red;
                nu_violate.Focus();
            }
            else if(lbl_status.Text=="添加")
            {
                MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=my_db1;UID=root;PWD=123456");
                conn.Open();
                string str = string.Format("select borrow_limit from reader_type where RTName='{0}'", RType);
                MySqlDataAdapter msda=new MySqlDataAdapter(str, conn);
                DataTable dt=new DataTable();
                msda.Fill(dt);
                conn.Close();
                int borrowLimit=-1;
                foreach (DataRow dr in dt.Rows)
                {
                    borrowLimit = int.Parse(dr["borrow_limit"].ToString());
                }
                if (currbor > borrowLimit)
                {
                    lbl_note.Text = "最多可借" + borrowLimit + "本！";
                    lbl_note.ForeColor = Color.Red;
                    nu_curr.Focus();
                }
                else
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand("addReader", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    //定义输入函数
                    cmd.Parameters.AddWithValue("rname_", RName);
                    cmd.Parameters.AddWithValue("rtype_", RType);
                    cmd.Parameters.AddWithValue("sex_", sex);
                    cmd.Parameters.AddWithValue("currbor_", currbor);
                    cmd.Parameters.AddWithValue("totalbor_", totalbor);
                    cmd.Parameters.AddWithValue("tel_", tel);
                    cmd.Parameters.AddWithValue("effi_", effiency);
                    cmd.Parameters.AddWithValue("state_", state);
                    cmd.Parameters.AddWithValue("violatenum_", violatenum);
                    cmd.Parameters.AddWithValue("remark_", remark);
                    //定义输出函数
                    MySqlParameter result = cmd.Parameters.Add("result", MySqlDbType.Int64);
                    result.Direction = ParameterDirection.Output;
                    cmd.ExecuteNonQuery();
                    if (result.Value.ToString() == "1")
                    {
                        lbl_note.Text = "恭喜你，添加成功！";
                        lbl_note.ForeColor = Color.Blue;
                        //trans.Commit();
                        //清空输入框
                        clearTextBox();
                        bind_reader_info();
                    }
                    else
                    {
                        lbl_note.Text = "对不起，添加失败！";
                        lbl_note.ForeColor = Color.Red;
                    }
                    conn.Close();
                }
            }
            else
            {
                MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=my_db1;UID=root;PWD=123456");
                conn.Open();
                string str = string.Format("select borrow_limit from reader_type where RTName='{0}'", RType);
                MySqlDataAdapter msda = new MySqlDataAdapter(str, conn);
                DataTable dt = new DataTable();
                msda.Fill(dt);
                conn.Close();
                int borrow_limit = int.Parse(dt.Rows[0]["borrow_limit"].ToString());
                if (currbor > borrow_limit)
                {
                    lbl_note.Text = "最多可借" + borrow_limit + "本！";
                    lbl_note.ForeColor = Color.Red;
                    nu_curr.Focus();
                }
                else
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand("updateReader", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    //定义输入函数
                    cmd.Parameters.AddWithValue("rrid_", rrid);
                    cmd.Parameters.AddWithValue("rname_", RName);
                    cmd.Parameters.AddWithValue("rtype_", RType);
                    cmd.Parameters.AddWithValue("sex_", sex);
                    cmd.Parameters.AddWithValue("currbor_", currbor);
                    cmd.Parameters.AddWithValue("totalbor_", totalbor);
                    cmd.Parameters.AddWithValue("tel_", tel);
                    cmd.Parameters.AddWithValue("effi_", effiency);
                    cmd.Parameters.AddWithValue("state_", state);
                    cmd.Parameters.AddWithValue("violatenum_", violatenum);
                    cmd.Parameters.AddWithValue("remark_", remark);
                    //定义输出函数
                    MySqlParameter result = cmd.Parameters.Add("result", MySqlDbType.Int64);
                    result.Direction = ParameterDirection.Output;
                    cmd.ExecuteNonQuery();
                    if (result.Value.ToString() == "1")
                    {
                        lbl_note.Text = "恭喜你，修改成功！";
                        lbl_note.ForeColor = Color.Blue;
                        //清空输入框
                        clearTextBox();
                        bind_reader_info();
                    }
                    else
                    {
                        lbl_note.Text = "对不起，修改失败！";
                        lbl_note.ForeColor = Color.Red;
                    }
                    conn.Close();
                }
            }
        }

        private void Frm_reader_manage_Load(object sender, EventArgs e)
        {
            bind_reader_info();
            lbl_mname.Text = mname;
            cb_rtype.SelectedIndex= 0;
            cmb_state.SelectedIndex = 1;
        }

        private void lv_reader_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lv_reader.SelectedItems.Count > 0)
            {
                ListViewItem myitem = lv_reader.SelectedItems[0];
                txt_RName.Text = myitem.SubItems[1].Text;
                cb_rtype.Text= myitem.SubItems[2].Text;
                btn_sex1.Checked = myitem.SubItems[3].Text =="男"?true:false;
                btn_sex2.Checked = !btn_sex1.Checked;
                nu_curr.Value = int.Parse(myitem.SubItems[5].Text);
                nu_total.Value = int.Parse(myitem.SubItems[6].Text);
                txt_tel.Text = myitem.SubItems[4].Text;
                dt_effi.Value = DateTime.ParseExact(myitem.SubItems[7].Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                cmb_state.Text = myitem.SubItems[12].Text;
                nu_violate.Value = int.Parse(myitem.SubItems[11].Text);
                txt_remark.Text= myitem.SubItems[13].Text;
                lbl_status.Text = "修改";
                rrid = int.Parse(myitem.SubItems[14].Text);
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            clearTextBox();
        }

        private void btn_del_Click(object sender, EventArgs e)
        {
            if (lv_reader.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择要删除的读者！");
            }
            else
            {
                DialogResult dResult = MessageBox.Show("确定要删除选择的读者？", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dResult == DialogResult.Yes)
                {
                    MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=my_db1;UID=root;PWD=123456");
                    conn.Open();
                    string str = string.Format("delete from reader_info where RRID={0}", rrid);
                    MySqlCommand cmd = new MySqlCommand(str, conn);
                    int i=cmd.ExecuteNonQuery();
                    if (i>0)
                    {
                        lbl_note.Text = "恭喜你，删除成功！";
                        lbl_note.ForeColor = Color.Blue;
                        //清空输入框
                        clearTextBox();
                        bind_reader_info();
                    }
                    else
                    {
                        lbl_note.Text = "对不起，删除失败！";
                        lbl_note.ForeColor = Color.Red;
                    }
                    conn.Close();
                }
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
}
